package org.linlinjava.litemall.wx.web;

import com.github.pagehelper.Page;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallCoupon;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallWithdraw;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.LitemallWithdrawService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxUserWithdrawService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户提现
 */
@RestController
@RequestMapping("/wx/withdraw")
@Validated
public class WxUserWithdrawController {
    private final Log logger = LogFactory.getLog(WxUserWithdrawController.class);

    @Autowired
    private WxUserWithdrawService userWithdrawService;

    @Autowired
    private LitemallUserService userService;


    @PostMapping("save")
    public Object save(@LoginUser Integer userId, @RequestBody LitemallWithdraw withdraw) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        LitemallUser user = userService.findById(userId);
        if(user.getBalance().compareTo(withdraw.getPrice()) < 0){
            return ResponseUtil.fail(-1,"提现金额大于可提现");
        }

        withdraw.setUserId(userId);
        withdraw.setAddTime(LocalDateTime.now());
        withdraw.setUpdateTime(LocalDateTime.now());
        withdraw.setStatus((byte) 0);
        withdraw.setDeleted(false);
        userWithdrawService.saveWithdraw(withdraw);

        return ResponseUtil.ok();
    }

    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        Page<LitemallWithdraw> couponList = userWithdrawService.queryList(userId, page, limit, sort, order);
        return ResponseUtil.okList(couponList);
    }
}
